﻿
using GameStates;
using UnityEngine;


public class GameRoot : MonoBehaviour
{
    public static GameRoot Instance { get; private set; }
    public static Common.CoroutineRoot CoroutineRoot { get; private set; }
    
    GameState m_CurrentState;

    private void Awake()
    {
        if (Instance != null)
        {
            Destroy(gameObject);
            return;
        }
        Instance = this;
        DontDestroyOnLoad(gameObject);
        var trans = transform;
        trans.position = Vector3.zero;
        trans.localScale = Vector3.zero;
        trans.rotation = Quaternion.identity;


        if (CoroutineRoot == null)
        {
            CoroutineRoot = new GameObject("CoroutineRoot").AddComponent<Common.CoroutineRoot>();
            DontDestroyOnLoad(CoroutineRoot);
            var coroutineRootTransform = CoroutineRoot.transform;
            coroutineRootTransform.position = Vector3.zero;
            coroutineRootTransform.localScale = Vector3.zero;
            coroutineRootTransform.rotation = Quaternion.identity;
        }
        
        ChangeState(GameState.Initialize);
    }
    

    
    private void Update()
    {
        m_CurrentState?.Update();
    }
    
    private void FixedUpdate()
    {        
        m_CurrentState?.FixedUpdate();
    }
    
    private void OnDestroy()
    {
    }
    
    public void ChangeState(GameState newState)
    {
        m_CurrentState?.OnExit();
        m_CurrentState = newState;
        m_CurrentState?.OnEnter();
    }
}
